package com.keepers.repair.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;

import com.keepers.repair.R;
import com.keepers.repair.helper.SpHelper;
import com.keepers.repair.helper.bus.LoginExitEvent;
import com.keepers.repair.helper.bus.RxBus;
import com.keepers.repair.net.AsyncOkHttpClient;
import com.keepers.repair.net.DataServiceProvider;
import com.keepers.repair.net.HttpUtil;
import com.keepers.repair.net.LoaderService;
import com.keepers.repair.net.RxTransformerHelper;
import com.keepers.repair.utils.AlertToast;
import com.keepers.repair.utils.UtilsKt;
import com.keepers.repair.view.TitleBar;

import io.reactivex.disposables.Disposable;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * auth aboom
 * date 2018/12/2
 */
public class NetSettingActivity extends BaseActivity {

    private boolean isTestSuccess;
    private String  p;
    private String  host;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_setting);
        TitleBar titleBar = f(R.id.title_bar);
        titleBar.initializeHeader("网络设置");
        TextInputEditText ip = findViewById(R.id.ip);
        TextInputEditText port = findViewById(R.id.port);
        String currentHttpHost = SpHelper.getCurrentHttpHost();
        int currentHttpPort = SpHelper.getCurrentHttpPort();
        boolean empty = TextUtils.isEmpty(currentHttpHost);
        ip.setText(empty ? HttpUtil.HTTP_HOST : currentHttpHost);
        port.setText(empty ? String.valueOf(HttpUtil.HTTP_PORT) : String.valueOf(currentHttpPort));
        f(R.id.button_test).setOnClickListener(v -> {
            if (!UtilsKt.isNetworkConnected()) {
                AlertToast.show("网络无连接...");
                return;
            }
            try {
                host = ip.getText().toString().trim();
                p = port.getText().toString().trim();
                LoaderService loaderService = new Retrofit.Builder()
                        .baseUrl(HttpUtil.getUrl(host, Integer.valueOf(p)))
                        .client(AsyncOkHttpClient.getOkHttpClient())
                        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                        .addConverterFactory(SimpleXmlConverterFactory.create())
                        .build().create(LoaderService.class);
                Disposable subscribe = loaderService.hello()
                        .compose(RxTransformerHelper.applySchedulersResult())
                        .subscribe(s -> {
                            if ("Hello World".equals(s)) {
                                isTestSuccess = true;
                                AlertToast.show("服务器网络访问成功...");
                            } else {
                                isTestSuccess = false;
                                AlertToast.show("服务器网络访问失败...");
                            }
                        }, throwable -> {
                            isTestSuccess = false;
                            AlertToast.show("服务器网络访问失败...");
                        });
                rxHelper.pend(subscribe);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        f(R.id.button_save).setOnClickListener(v -> {
            String ipStr = ip.getText().toString().trim();
            String portStr = port.getText().toString().trim();
            if (isTestSuccess && ipStr.equals(host) && portStr.equals(p)) {
                try {
                    SpHelper.setCurrentHttpHost(ipStr);
                    SpHelper.setCurrentHttpPort(Integer.valueOf(portStr));
                    DataServiceProvider.getInstance().reloadService(HttpUtil.getUrl(ipStr, Integer.valueOf(portStr)));
                    LoginExitEvent loginExitEvent = new LoginExitEvent();
                    loginExitEvent.isReloadSocket = true;
                    RxBus.getDefault().post(loginExitEvent);
                    AlertToast.show("变更成功...");
                    finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                AlertToast.show("请先测试服务器网络成功后再进行保存...");
            }
        });
    }
}
